//
//  NetworkTools.swift
//  WJWeibo
//
//  Created by Jie on 15/12/19.
//  Copyright © 2015年 周文杰. All rights reserved.
//
// app key :2527572959
//App Secret：4dc9783e3bdfdc8fcf07c9fee3fd2e53


import UIKit

import AFNetworking
class NetworkTools: AFHTTPSessionManager {

    //MARK: - 属性
    //app key
    private let appKey = "2527572959"
    //app 秘钥
    private let appSecret = "4dc9783e3bdfdc8fcf07c9fee3fd2e53"

    
    //授权回调地址
    let redirect_uri = "http://www.baidu.com/"
    let grant_type = "authorization_code"
    
    //MARK：- 构造方法
    ///单例
    static let shadredInstance: NetworkTools = NetworkTools()
    //构造方法
    private init() {
        let baseURL = NSURL(string: "https://api.weibo.com/")!
        //在构造函数里面子类不能调用父类的便利构造函数，需要调用父类的制定构造函数
        super.init(baseURL: baseURL, sessionConfiguration: nil)
        
        //设置响应的序列化器，支持text/plain
        self.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 网络请求方法
    ///返回URL，可获得code
    func oauthUrl() -> NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirect_uri)"
        return NSURL(string: urlString)!
    }
    
    ///根据code 获得AccessToken
    func loadAccessToken(code: String, finished: (result: [String: AnyObject]?, error: NSError?) ->()) {
        //url地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //请求参数，字典
        let parameters = [
            "client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        //发送POST请求
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
//            print("\(result)")
            //将返回的字典转为结果
            let dict = result as? [String : AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
//                print("\(error)")
                finished(result: nil, error: error)
        }
        
    }
    
    
    
}
